﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using Web_Oto.Business;
using Web_Oto.Common;

namespace Web_Oto
{
    public partial class Ajax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var action = Request["action"];
            switch (action)
            {
                case "Contact":
                    SendContact();
                    break;
            }
        }

        private void AddContact(string description)
        {
            var contactBus = new ContactBus();
            contactBus.Save(description);
        }

        private void SendContact()
        {
            var fullName = Request["fullname"];
            var email = Request["email"];
            var content = Request["content"];
            AddContact(content);
            if (CommonHelper.IsValidEmail(email))
            {
                string mailTo = ConfigurationManager.AppSettings["Mailto"];
                var sentmail = SendEmail(fullName, email, mailTo, "Contact from " + fullName, content);
                Response.Write(sentmail?"Chúng tôi đã nhận được yêu cầu":"Lỗi gửi yêu cầu");
            }
            else
                Response.Write("Email không đúng định dạng");
        }

        private bool SendEmail(string fullName, string emailFrom, string emailTo, string subject, string body)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(emailFrom, fullName);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            try
            {
                SmtpClient smtp = new SmtpClient("127.0.0.1");
                smtp.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}